package com.ruoyi.api.v1;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.cinema.BO.BindCouponBO;
import com.ruoyi.cinema.BO.CardRulePlusBO;
import com.ruoyi.cinema.BO.DecryptPhoneBO;
import com.ruoyi.cinema.BO.GetCardRuleBO;
import com.ruoyi.cinema.DTO.CardInfoYzDTO;
import com.ruoyi.cinema.DTO.CardRuleInfoYzDTO;
import com.ruoyi.cinema.DTO.CouponInfoYzDTO;
import com.ruoyi.cinema.domain.Customer;
import com.ruoyi.cinema.service.ICustomerService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.AesCbcUtil;
import com.ruoyi.utils.WechatUtils;
import com.ruoyi.utils.YzPage;
import com.ruoyi.utils.YzResult;
import com.ruoyi.utils.YzUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController("v1_Customer")
@RequestMapping(value = "api/v1/customer")
public class CustomerController extends BaseController {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private RedisCache redisCache;

    @GetMapping(value = "/insert")
    public AjaxResult insert(Customer customer){
        if(StringUtils.isEmpty(customer.getOpenIdCode())){
            AjaxResult.error(-1,"openIdCode 不能为空");
        }

        JSONObject wechatLoginRet =  WechatUtils.jscode2session(customer.getOpenIdCode());
        if(null == wechatLoginRet.getString("openid")){
           return AjaxResult.error(-1,"换取openId失败");
        }
        customer.setOpenId(wechatLoginRet.getString("openid"));
        Customer cus = customerService.getOne(new QueryWrapper<Customer>().eq("open_id",customer.getOpenId()));
        if(null == cus){
            customer.setSessionKey(wechatLoginRet.getString("session_key"));
            customerService.insertCustomer(customer);
            cus = customer;
        }else {
            cus.setSessionKey(wechatLoginRet.getString("session_key"));
            customerService.updateCustomer(cus);
        }
        return AjaxResult.success(cus);
    }

    @GetMapping(value = "/get")
    public AjaxResult get(Customer customer){
        if(null == customer.getId()){
            AjaxResult.error(-1,"customerId 不能为空");
        }
        Customer  cus = customerService.selectCustomerById(customer.getId());
        return AjaxResult.success(cus);
    }

    @RequestMapping(value = "/update")
    public AjaxResult update(@RequestBody Customer customer){
        if(null == customer.getId()){
            AjaxResult.error(-1,"customerId 不能为空");
        }
        return toAjax(customerService.updateCustomer(customer));

    }

    @GetMapping(value = "/bindYZ")
    public AjaxResult bind(Customer customer) {
        if(null == customer.getId()){
            AjaxResult.error(-1,"customerId 不能为空");
        }
        if(StringUtils.isEmpty(customer.getPhone())){
            AjaxResult.error(-1,"phone 不能为空");
        }

        if(!Validator.isMobile(customer.getPhone())){
            AjaxResult.error(-1,"手机号不合法");
        }
        Customer cus = customerService.bindYZ(customer);
        return AjaxResult.success(cus);
    }

    @PostMapping(value = "/decryptPhone")
    public AjaxResult decryptPhone(@RequestBody DecryptPhoneBO decryptPhoneBO){
        if(null == decryptPhoneBO.getId()){
            return AjaxResult.error(-1,"customerId 不能为空");
        }
        if(StringUtils.isEmpty(decryptPhoneBO.getEncryptedData()) || StringUtils.isEmpty(decryptPhoneBO.getIv())){
            return AjaxResult.error(-1,"EncryptedData 或者 iv 为空");
        }
        Customer customer = customerService.selectCustomerById(decryptPhoneBO.getId());
        if(null == customer || StringUtils.isEmpty(customer.getSessionKey())){
            return AjaxResult.error(-1," 用户找不到，或者sessionkey找不到，请先insert 用户");
        }
        String json = "";
        try {
            json =  AesCbcUtil.decrypt(decryptPhoneBO.getEncryptedData(),customer.getSessionKey(),decryptPhoneBO.getIv(),"UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        if(StringUtils.isEmpty(json)){
            return AjaxResult.error(-1,"解密失败");
        }
        System.out.println(json);
        Map mapret = JSON.parseObject(json, Map.class);
        return AjaxResult.success(mapret);

    }

    @GetMapping(value = "/pushRefreshToken")
    public AjaxResult pushRefreshToken(String code,String mode){
        redisCache.setCacheObject(Constants.YZ_REFRESH_TOKEN,code,14L, TimeUnit.DAYS);
        logger.info("--------this is push refresh token");
        return AjaxResult.success("ok");
    }

    @GetMapping(value = "/getMyCardList")
    public AjaxResult getMyCardList(Customer customer){
        if(null == customer.getId()){
            return AjaxResult.error(-1,"customerId 不能为空");
        }
        Customer cu = customerService.selectCustomerById(customer.getId());
        if(null == cu){
            return AjaxResult.error(-1,"未找到对应的用户");
        }
        String accessToken = customerService.getAccessToken(cu.getId(),cu.getPhone());
        YzResult<CardInfoYzDTO> ret = YzUtils.getCardList(accessToken);
        return AjaxResult.success(ret);
    }

    //获取卡续费列表
    @GetMapping(value = "/getCardRecharge")
    public AjaxResult getCardRecharge(GetCardRuleBO getCardRuleBO){
        if(StringUtils.isEmpty(getCardRuleBO.getCardNo())){
            return AjaxResult.error(-1,"cardNo 不能为空");
        }
        Customer customer = customerService.selectCustomerById(getCardRuleBO.getCustomerId());
        if(null == customer){
            return AjaxResult.error(-1,"找不到对应的customer");
        }
        String accessToken = customerService.getAccessToken(customer.getId(),customer.getPhone());
        YzResult<CardInfoYzDTO> cardInfoYzDTOYzResult = YzUtils.getCardInfo(accessToken,getCardRuleBO.getCardNo());
        if(!cardInfoYzDTOYzResult.getResultCode().equals(Constants.YZSUCCESS) || !cardInfoYzDTOYzResult.getData().getBizCode().equals(Constants.BIZSUCCESS)){
            return AjaxResult.error(-1,"获取失败");
        }
        CardInfoYzDTO cardInfoYzDTO = cardInfoYzDTOYzResult.getData().getBizData();
        if(null == cardInfoYzDTO){
            return AjaxResult.error(-1,"获取失败");
        }
        YzResult<CardRuleInfoYzDTO> cardRuleInfoYzDTOYzResult =  YzUtils.getCardRuleInfo(cardInfoYzDTO.getCardRuleId());
        if(cardRuleInfoYzDTOYzResult.getResultCode().equals(Constants.YZSUCCESS) && cardRuleInfoYzDTOYzResult.getData().getBizCode().equals(Constants.BIZSUCCESS)){
            CardRuleInfoYzDTO cardRuleInfoYzDTO = cardRuleInfoYzDTOYzResult.getData().getBizData();
            List<CardRulePlusBO> cardRulePlusBOList = new LinkedList<>();
            if(null != cardRuleInfoYzDTO){
                getCardRuleBO.setCardType(cardRuleInfoYzDTO.getCardType());
                if(cardRuleInfoYzDTO.getCardType().equals("BENEFIT")){
                    CardRulePlusBO cardRulePlusBO = new CardRulePlusBO();
                    cardRulePlusBO.setAmount(cardRuleInfoYzDTO.getMembershipFee());
                    if(cardRuleInfoYzDTO.getRechargeExpireTimeUnit().equals("DAY")){
                        cardRulePlusBO.setAddDay(cardRuleInfoYzDTO.getRechargeExpireTimeValue());
                    }
                    if(cardRuleInfoYzDTO.getRechargeExpireTimeUnit().equals("MONTH")){
                        cardRulePlusBO.setAddMonth(cardRuleInfoYzDTO.getRechargeExpireTimeValue());
                    }
                    if(cardRuleInfoYzDTO.getRechargeExpireTimeUnit().equals("YEAR")){
                        cardRulePlusBO.setAddYear(cardRuleInfoYzDTO.getRechargeExpireTimeValue());
                    }
                    cardRulePlusBOList.add(cardRulePlusBO);
                }
                if(cardRuleInfoYzDTO.getCardType().equals("DEPOSIT")){

                    if(null != cardRuleInfoYzDTO.getRechargeGradeAmountList()){

                        for (Long amount :cardRuleInfoYzDTO.getRechargeGradeAmountList()) {
                            CardRulePlusBO cardRulePlusBO = new CardRulePlusBO();
                            cardRulePlusBO.setAmount(amount);
                            cardRulePlusBO.setAddAmount(amount);
                            cardRulePlusBOList.add(cardRulePlusBO);
                        }
                    }
                }

                getCardRuleBO.setCardRulePlusList(cardRulePlusBOList);
                return AjaxResult.success(getCardRuleBO);
            }
        }
        return AjaxResult.error(-1,"获取失败");
    }


    @PostMapping("/bindCoupon")
    public AjaxResult bindCoupon(@RequestBody BindCouponBO bindCouponBO){
        return AjaxResult.error(-1,"暂时不支持绑定会员卡");

//        if(StringUtils.isEmpty(bindCouponBO.getCouponCode())){
//            return AjaxResult.error(-1,"优惠券号不能为空");
//        }
//        if(null == bindCouponBO.getCustomerId()){
//            return AjaxResult.error(-1,"customerId不能为空");
//        }
//
//        String accessToken = customerService.getAccessToken(bindCouponBO.getCustomerId());
//        if(StringUtils.isEmpty(accessToken)){
//            return AjaxResult.error(-1,"获取accessToken失败，请先绑定手机号");
//        }
//        YzResult<String> ret = YzUtils.bindingCoupon(bindCouponBO.getCouponCode(),accessToken);
//        if(!ret.getResultCode().equals(Constants.YZSUCCESS)){
//           return AjaxResult.error(-1,"请求失败");
//        }
//        if(ret.getResultCode().equals(Constants.YZSUCCESS)&& ret.getData().getBizCode().equals(Constants.BIZSUCCESS)){
//            return AjaxResult.success("绑定成功");
//        }else {
//            return AjaxResult.error(-1,ret.getData().getBizMsg());
//        }
    }

    @GetMapping("/getCouponList")
    public TableDataInfo getCouponList(Customer customer){
        if(null == customer.getId()){
            return getDataTableError(-1,"customerId不能为空");
        }
        String accessToken = customerService.getAccessToken(customer.getId());
        if(StringUtils.isEmpty(accessToken)){
            return getDataTableError(-1,"获取accessToken失败，请先绑定手机号");
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNo = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if(StringUtils.isNull(pageNo) || StringUtils.isNull(pageSize)){
            return getDataTableError(-1,"请传分页参数");
        }
        if(pageSize > 20){
            return getDataTableError(-1,"最大为20条");
        }
        YzResult<CouponInfoYzDTO> ret = YzUtils.getCouponPageList(pageNo,pageSize,accessToken);
        if(ret.getResultCode().equals(Constants.YZSUCCESS) && ret.getData().getBizCode().equals(Constants.BIZSUCCESS)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(ret.getData().getBizDataList());
            YzPage yzPage = ret.getData().getPageInfo();
            rspData.setTotal(yzPage.getItemsPerPage());
            rspData.setHasNextPage(yzPage.getCurPage() < yzPage.getTotalPage());
            return rspData;
        }
        return getDataTableError(-1,"获取失败");
    }


}
